import * as step from '@flow-step/step-toolkit'
import process from 'process'
import fs from 'fs'
import * as sinon from 'sinon'
import {expect} from 'chai'
import {afterEach, beforeEach} from 'mocha'
// @ts-ignore
import * as install from '../src/install'

let sandbox = sinon.createSandbox()
let addPath: sinon.SinonStub
let stepInstallStub: sinon.SinonStub

let chmodSyncStub: sinon.SinonStub

beforeEach(() => {
    sandbox.stub(process, 'env').value({
        ...process.env,
        FLOW_TOOL_REGISTRY_URL: 'https://tool-registry-url.com',
        FLOW_RUNNER_TOOL_CACHE_DIR: '/tmp/flow_tools'
    })

    addPath = sandbox.stub(step, 'addPath')
    stepInstallStub = sandbox.stub(step.tool, 'install')

    chmodSyncStub = sandbox.stub(fs, 'chmodSync')
})

afterEach(() => {
    sandbox.restore()
})


describe('install kubectl', () => {
    it('install kubectl', async () => {
        const installPath = '/path/to/install'
        stepInstallStub.resolves(installPath)

        const kubectlVersion = 'v1.28.2'
        const result = await install.installKubectl(kubectlVersion)
        expect(result).to.equal(installPath)
        expect(stepInstallStub.callCount).to.equal(1)
        sinon.assert.calledWith(stepInstallStub, 'kubectl', kubectlVersion)
        sinon.assert.calledWith(chmodSyncStub, `${installPath}/kubectl-${kubectlVersion}`, 0o755)
        sinon.assert.calledWith(addPath, installPath)

    })
})

afterEach(() => {
    process.env.FLOW_RUNNER_TOOL_CACHE_DIR = ''
})